package com.itheima.reggin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggin.common.R;
import com.itheima.reggin.entity.Category;
import com.itheima.reggin.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 * @author YUCH
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategroyController {

    @Autowired
    CategoryService categroyService;

    /**
     * 增
     * @param categroy
     * @return
     */
    @PostMapping
    public R<String> add(@RequestBody Category categroy) {

        categroyService.save(categroy);
        return R.success("菜品添加成功！");
    }

    /**
     * 查
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.orderByDesc(Category::getSort);
        categroyService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids) {
        categroyService.remove(ids);
        return R.success("删除成功！");
    }

    /**
     * 改
     * @param category
     * @return
     */
    @PutMapping
    public R<String> alter(@RequestBody Category category){
        categroyService.updateById(category);
        return R.success("修改成功！");
    }

    /**
     * 新增dish时，查询菜品分类下拉列表
     */
    @GetMapping("/list")
    public R<List<Category>> list( Category category){
        Integer type = category.getType();
        LambdaQueryWrapper<Category> query = new LambdaQueryWrapper<>();
        query.eq(category.getType()!=null,Category::getType,type);
        query.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categroyService.list(query);
        return R.success(list);
    }
}
